package controllers

import (
	"finance/internal/dto"
	"finance/internal/models"
	"finance/internal/utils"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"net/http"
)

// CreateUser @Summary Create a new user with role
// @Description Create user and assign role in a transaction
// @Tags user
// @Accept json
// @Produce json
// @Param user body dto.CreateUserRequest true "User info"
// @Success 200 {object} utils.Response
// @Failure 400 {object} utils.Response
// @Router /user/create [post]
func CreateUser(c *gin.Context) {
	var req dto.CreateUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Fail(c, http.StatusBadRequest, "Invalid JSON request")
		return
	}

	err := models.DB.Transaction(func(tx *gorm.DB) error {
		// 检查用户名是否存在
		existingUser, err := models.GetUserByUsername(req.Username)
		if err != nil {
			utils.Fail(c, http.StatusInternalServerError, err.Error())
			return err
		}
		if existingUser != nil {
			utils.Fail(c, http.StatusBadRequest, "Username already exists")
			return err
		}

		// bcrypt 加密密码
		hashedPwd, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
		if err != nil {
			return err
		}

		user := models.User{
			Username: req.Username,
			Password: string(hashedPwd),
			RealName: req.RealName,
			Status:   "active",
			Role:     req.Role,
		}

		// 创建用户
		if err := tx.Create(&user).Error; err != nil {
			return err
		}

		// 获取 role_id
		roleID, err := models.GetRoleIDByName(req.Role)
		if err != nil {
			return err
		}

		// 插入 user_roles
		userRole := models.UserRole{
			UserID: user.ID,
			RoleID: uint(roleID),
		}
		if err := tx.Create(&userRole).Error; err != nil {
			return err
		}

		return nil // 没有错误，事务提交
	})

	if err != nil {
		utils.Fail(c, http.StatusInternalServerError, err.Error())
		return
	}

	utils.Success(c, gin.H{
		"msg": "User created successfully",
	})
}
